using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AppManagement.Repositories
{
	#region using
	using AppManagement.Models;
	#endregion
	public class BenhNhanRepository
	{
		public static List<BenhNhan> SelectAll()
		{
			return DataContext.Instance.BenhNhans.OrderBy(item => item.Ten).ToList();
		}

		public static BenhNhan SelectByID(string mabn)
		{
			return DataContext.Instance.BenhNhans.FirstOrDefault(item => item.MaBN == mabn );
		}

		public static bool Insert(BenhNhan obj)
		{
			try
			{
				DataContext.Instance.BenhNhans.AddObject(obj);
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool Delete(string mabn)
		{
			try
			{
				var delitem = DataContext.Instance.BenhNhans.FirstOrDefault(item => item.MaBN == mabn );
				DataContext.Instance.BenhNhans.DeleteObject(delitem);
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool Save()
		{
			try
			{
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static List<BenhNhan> RetrieveByID(string mabn)
		{
			return (from item in DataContext.Instance.BenhNhans where  item.MaBN == mabn  select item).ToList();
		}

        public static List<BenhNhan> Search(string id, string ho, string ten)
        {
            var lst = new List<BenhNhan>();
            foreach (var item in DataContext.Instance.BenhNhans)
            {
                if (item.MaBN.Trim() == (id == "" ? item.MaBN.Trim() : id) &&
                    item.Ho.ToUpper().Contains(ho == "" ? item.Ho.ToUpper() : ho.Trim().ToUpper()) &&
                    item.Ten.ToUpper().Contains(ten == "" ? item.Ten.ToUpper() : ten.Trim().ToUpper()))
                {
                    lst.Add(item);
                }
            }
            return lst;
        }
	}
}